package com.yanq.liancar.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.Callback;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.vondear.rxtool.RxActivityTool;
import com.vondear.rxtool.RxPhotoTool;
import com.vondear.rxtool.view.RxToast;
import com.vondear.rxui.view.dialog.RxDialogChooseImage;
import com.yalantis.ucrop.UCrop;
import com.yalantis.ucrop.UCropActivity;
import com.yanq.liancar.R;
import com.yanq.liancar.activity.base.BaseToolbarActivity;
import com.yanq.liancar.adapter.GvServiceImgAdapter2;
import com.yanq.liancar.bean.BaseBean;
import com.yanq.liancar.bean.ShopInformationBean;
import com.yanq.liancar.bean.UserBean;
import com.yanq.liancar.url.Config;
import com.yanq.liancar.util.LogUtils;
import com.yanq.liancar.util.ToastUtils;
import com.yanq.liancar.util.Utils;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class SmallBInformationActivity extends BaseToolbarActivity {
    @BindView(R.id.img_shopbg)
    ImageView imgShopbg;
    @BindView(R.id.rl_shopbg)
    RelativeLayout rlShopbg;
    @BindView(R.id.tv_shopname)
    TextView tvShopname;
    @BindView(R.id.rl_shopname)
    RelativeLayout rlShopname;
    @BindView(R.id.tv_shopphone)
    TextView tvShopphone;
    @BindView(R.id.rl_shopphone)
    RelativeLayout rlShopphone;
    @BindView(R.id.tv_shopaddress)
    TextView tvShopaddress;
    @BindView(R.id.rl_shopaddress)
    RelativeLayout rlShopaddress;
    @BindView(R.id.tv_shopabstract)
    TextView tvShopabstract;
    @BindView(R.id.rl_shopabstract)
    RelativeLayout rlShopabstract;
    @BindView(R.id.img_license)
    ImageView imgLicense;
    @BindView(R.id.rl_license)
    RelativeLayout rlLicense;

    private Uri resultUri;
    private File file1, file2;
    private int succ, type, statu;   //succ:点击的哪个图片   type：新增或修改   status：
    private LinkedList<String> imgIdList=new LinkedList<>();
    private ShopInformationBean baseBean;
    private LinkedList<Integer> typeList = new LinkedList<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_small_b_information);
        Utils.setStatusBar(this, true, false);
        ButterKnife.bind(this);
        mTvTitle.setText("店铺信息");
        mTvRight.setVisibility(View.VISIBLE);
        mTvRight.setText("保存");
        mTvRight.setTextColor(getResources().getColor(R.color.main_color));

        mTvRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (type == 1) {
                    addStores();
                } else if (type == 2) {
                    modifyStores();
                }
            }
        });
        getStores();
    }

    @OnClick({R.id.rl_shopbg, R.id.rl_shopname, R.id.rl_shopphone, R.id.rl_shopaddress, R.id.rl_shopabstract, R.id.rl_license})
    public void onViewClicked(View view) {
        RxDialogChooseImage dialogChooseImage = new RxDialogChooseImage(this);
        switch (view.getId()) {
            case R.id.rl_shopbg:
                succ = 1;
                dialogChooseImage.show();
                break;
            case R.id.rl_shopname:
                Bundle bundle = new Bundle();
                bundle.putString("content", "店铺名称");
                RxActivityTool.skipActivityForResult(this, SmallCEditActivity.class, bundle, 1);
                break;
            case R.id.rl_shopphone:
                Bundle bundle1 = new Bundle();
                bundle1.putString("content", "联系电话");
                RxActivityTool.skipActivityForResult(this, SmallCEditActivity.class, bundle1, 2);
                break;
            case R.id.rl_shopaddress:
                Bundle bundle2 = new Bundle();
                bundle2.putString("content", "店铺地址");
                RxActivityTool.skipActivityForResult(this, SmallCEditActivity.class, bundle2, 3);
                break;
            case R.id.rl_shopabstract:
                Bundle bundle3 = new Bundle();
                bundle3.putString("content", "店铺简介");
                RxActivityTool.skipActivityForResult(this, SmallCEditActivity.class, bundle3, 4);
                break;
            case R.id.rl_license:
                succ = 2;
                dialogChooseImage.show();
                break;
        }
    }

    //查询店铺信息
    private void getStores() {
        OkGo.<String>post(Config.s + "llc/shop/queryShopMsg")
                .tag(this)
                .params("token", UserBean.getbToken(mContext))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        baseBean = gson.fromJson(response.body(), ShopInformationBean.class);
                        if (baseBean.isIsSuccess()) {
                            LogUtils.e("baseBean.getData()===", baseBean.getData() + "");
                            if (null != baseBean.getData()) {
                                type = 2;
                                tvShopname.setText(baseBean.getData().getShopName());
                                tvShopphone.setText(baseBean.getData().getShopTel());
                                tvShopaddress.setText(baseBean.getData().getShopAddress());
                                tvShopabstract.setText(baseBean.getData().getShopMsg());
                                RequestOptions options=new RequestOptions();

                                if (baseBean.getData().getShopPages().size() > 0) {
                                    options.placeholder(R.mipmap.shop_bg);
                                    Glide.with(mContext).load(baseBean.getData().getShopPages().get(0).getWebPath()).apply(options).into(imgShopbg);
                                }
                                if (baseBean.getData().getBusLic().size() > 0) {
                                    options.placeholder(R.mipmap.license_bg);
                                    Glide.with(mContext).load(baseBean.getData().getBusLic().get(0).getWebPath()).apply(options).into(imgLicense);
                                }
                            } else {
                                type = 1;
                            }
                            LogUtils.e("type===", type + "");
                        }
                    }
                });
    }


    //添加店铺信息
    private void addStores() {
        OkGo.<String>post(Config.s + "llc/shop/addShop")
                .tag(this)
                .params("token", UserBean.getbToken(mContext))
                .params("shopName", tvShopname.getText().toString().trim())
                .params("shopMsg", tvShopabstract.getText().toString().trim())
                .params("shopTel", tvShopphone.getText().toString().trim())
                .params("shopAddress", tvShopaddress.getText().toString().trim())
                .params("backPage", file1)
                .params("licPage", file2)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        BaseBean baseBean = gson.fromJson(response.body(), BaseBean.class);
                        if (baseBean.isIsSuccess()) {
                            RxToast.success("保存成功");
                        } else {
                            RxToast.error(baseBean.getOutputMessage());
                        }
                    }
                });

    }

    //修改店铺信息
    private void modifyStores() {
        //说明更改的时logo
        if (typeList.size() == 2) {
            LogUtils.e("z走的这里=====", "22222222222====" + statu);
            OkGo.<String>post(Config.s + "llc/shop/updateShopMsg")
                    .tag(this)
                    .params("id", baseBean.getData().getId())
                    .params("token", UserBean.getbToken(mContext))
                    .params("shopName", tvShopname.getText().toString().trim())
                    .params("shopMsg", tvShopabstract.getText().toString().trim())
                    .params("shopTel", tvShopphone.getText().toString().trim())
                    .params("shopAddress", tvShopaddress.getText().toString().trim())
                    .params("backPage", file1)
                    .params("licPage", file2)
                    .execute(new StringCallback() {
                        @Override
                        public void onSuccess(Response<String> response) {
                            Gson gson = new Gson();
                            BaseBean baseBean = gson.fromJson(response.body(), BaseBean.class);
                            if (baseBean.isIsSuccess()) {
                                RxToast.success(baseBean.getOutputMessage());
                                initOkGoDelImg();
                            } else {
                                RxToast.error(baseBean.getOutputMessage());
                            }
                        }
                    });
            //说明更改的时营业执照
        } else if (typeList.size() == 0) {
            //没有修改图片信息
            LogUtils.e("z走的这里=====", "33333333333333====" + statu);
            OkGo.<String>post(Config.s + "llc/shop/updateShopMsg")
                    .tag(this)
                    .params("id", baseBean.getData().getId())
                    .params("token", UserBean.getbToken(mContext))
                    .params("shopName", tvShopname.getText().toString().trim())
                    .params("shopMsg", tvShopabstract.getText().toString().trim())
                    .params("shopTel", tvShopphone.getText().toString().trim())
                    .params("shopAddress", tvShopaddress.getText().toString().trim())
                    .execute(new StringCallback() {
                        @Override
                        public void onSuccess(Response<String> response) {
                            Gson gson = new Gson();
                            BaseBean baseBean = gson.fromJson(response.body(), BaseBean.class);
                            if (baseBean.isIsSuccess()) {
                                RxToast.success(baseBean.getOutputMessage());
                            } else {
                                RxToast.error(baseBean.getOutputMessage());
                            }
                        }
                    });
        } else if (typeList.size() == 1) {
            if (typeList.get(0) == 1) {

                LogUtils.e("z走的这里=====", "1111111111111====" + statu);
                OkGo.<String>post(Config.s + "llc/shop/updateShopMsg")
                        .tag(this)
                        .params("id", baseBean.getData().getId())
                        .params("token", UserBean.getbToken(mContext))
                        .params("shopName", tvShopname.getText().toString().trim())
                        .params("shopMsg", tvShopabstract.getText().toString().trim())
                        .params("shopTel", tvShopphone.getText().toString().trim())
                        .params("shopAddress", tvShopaddress.getText().toString().trim())
                        .params("backPage", file1)
                        .execute(new StringCallback() {
                            @Override
                            public void onSuccess(Response<String> response) {
                                Gson gson = new Gson();
                                BaseBean baseBean = gson.fromJson(response.body(), BaseBean.class);
                                if (baseBean.isIsSuccess()) {
                                    RxToast.success(baseBean.getOutputMessage());
                                    initOkGoDelImg();
                                } else {
                                    RxToast.error(baseBean.getOutputMessage());
                                }
                            }
                        });
            } else {
                LogUtils.e("z走的这里=====", "22222222222====" + statu);
                OkGo.<String>post(Config.s + "llc/shop/updateShopMsg")
                        .tag(this)
                        .params("id", baseBean.getData().getId())
                        .params("token", UserBean.getbToken(mContext))
                        .params("shopName", tvShopname.getText().toString().trim())
                        .params("shopMsg", tvShopabstract.getText().toString().trim())
                        .params("shopTel", tvShopphone.getText().toString().trim())
                        .params("shopAddress", tvShopaddress.getText().toString().trim())
                        .params("licPage", file2)
                        .execute(new StringCallback() {
                            @Override
                            public void onSuccess(Response<String> response) {
                                Gson gson = new Gson();
                                BaseBean baseBean = gson.fromJson(response.body(), BaseBean.class);
                                if (baseBean.isIsSuccess()) {
                                    RxToast.success(baseBean.getOutputMessage());
                                    initOkGoDelImg();
                                } else {
                                    RxToast.error(baseBean.getOutputMessage());
                                }
                            }
                        });
            }
        }
    }

    //删除图片
    private void initOkGoDelImg() {
        OkGo.<String>post(Config.s + "llc/fileController/deleteFilesByIds")
                .tag(this)
                .params("token", UserBean.getbToken(mContext))
                .addUrlParams("ids", imgIdList)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        BaseBean baseBean = gson.fromJson(response.body(), BaseBean.class);
                        if (baseBean.isIsSuccess()) {

                        } else {
                            //RxToast.error(baseBean.getOutputMessage());
                        }
                    }
                });

    }

    private void initUCrop(Uri uri) {
        //Uri destinationUri = RxPhotoTool.createImagePathUri(this);

        SimpleDateFormat timeFormatter = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA);
        long time = System.currentTimeMillis();
        String imageName = timeFormatter.format(new Date(time));

        Uri destinationUri = Uri.fromFile(new File(getCacheDir(), imageName + ".jpeg"));

        Log.e("initUCrop: ", destinationUri + "");

        UCrop.Options options = new UCrop.Options();
        //设置裁剪图片可操作的手势
        options.setAllowedGestures(UCropActivity.SCALE, UCropActivity.ROTATE, UCropActivity.ALL);
        //设置隐藏底部容器，默认显示
        //options.setHideBottomControls(true);
        //设置toolbar颜色
        options.setToolbarColor(ActivityCompat.getColor(this, R.color.main_color));
        //设置状态栏颜色
        options.setStatusBarColor(ActivityCompat.getColor(this, R.color.main_color));

        //开始设置
        //设置最大缩放比例
        options.setMaxScaleMultiplier(5);
        //设置图片在切换比例时的动画
        options.setImageToCropBoundsAnimDuration(666);
        //设置裁剪窗口是否为椭圆
//        options.setOvalDimmedLayer(true);
        //设置是否展示矩形裁剪框
        options.setShowCropFrame(true);
        //设置裁剪框横竖线的宽度
        //options.setCropGridStrokeWidth(20);
        //设置裁剪框横竖线的颜色
        //options.setCropGridColor(Color.GREEN);
        //设置竖线的数量
        //options.setCropGridColumnCount(2);
        //设置横线的数量
        //options.setCropGridRowCount(1);

        UCrop.of(uri, destinationUri)
                .withAspectRatio(1, 1)
                .withMaxResultSize(1000, 1000)
                .withOptions(options)
                .start(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        initMySelfImg(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
        if (data!=null){
            if (requestCode == 1) {
                tvShopname.setText(data.getStringExtra("content"));
            } else if (requestCode == 2) {
                tvShopphone.setText(data.getStringExtra("content"));
            } else if (requestCode == 3) {
                tvShopaddress.setText(data.getStringExtra("content"));
            } else if (requestCode == 4) {
                tvShopabstract.setText(data.getStringExtra("content"));
            }
        }
    }

    private void initMySelfImg(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case RxPhotoTool.GET_IMAGE_FROM_PHONE://选择相册之后的处理
                if (resultCode == RESULT_OK) {
                    initUCrop(data.getData());
                }

                break;
            case RxPhotoTool.GET_IMAGE_BY_CAMERA://选择照相机之后的处理
                if (resultCode == RESULT_OK) {
                    initUCrop(RxPhotoTool.imageUriFromCamera);
                }

                break;
            case RxPhotoTool.CROP_IMAGE://普通裁剪后的处理
                resultUri = RxPhotoTool.cropImageUri;
                if (succ == 1) {
                    file1 = roadImageView(resultUri, imgShopbg);
                    statu = 1;
                    typeList.add(1);
                    if (type == 2) {
                        if (baseBean.getData().getShopPages().size() > 0) {
                            imgIdList.add(baseBean.getData().getShopPages().get(0).getId() + "");
                        }
                    }
                } else {
                    file2 = roadImageView(resultUri, imgLicense);
                    statu = 2;
                    typeList.add(2);
                    if (type == 2) {
                        if (baseBean.getData().getBusLic().size() > 0) {
                            imgIdList.add(baseBean.getData().getBusLic().get(0).getId() + "");
                        }
                    }
                }

                break;

            case UCrop.REQUEST_CROP://UCrop裁剪之后的处理
                if (resultCode == RESULT_OK) {
                    resultUri = UCrop.getOutput(data);
                    if (succ == 1) {
                        file1 = roadImageView(resultUri, imgShopbg);
                        statu = 1;
                        typeList.add(1);
                        if (type == 2) {
                            if (baseBean.getData().getShopPages().size() > 0) {
                                imgIdList.add(baseBean.getData().getShopPages().get(0).getId() + "");
                            }
                        }
                    } else {
                        file2 = roadImageView(resultUri, imgLicense);
                        statu = 2;
                        typeList.add(2);
                        if (type == 2) {
                            if (baseBean.getData().getBusLic().size() > 0) {
                                imgIdList.add(baseBean.getData().getBusLic().get(0).getId() + "");
                            }
                        }
                    }
                } else if (resultCode == UCrop.RESULT_ERROR) {
                    final Throwable cropError = UCrop.getError(data);
                }
                break;
            case UCrop.RESULT_ERROR://UCrop裁剪错误之后的处理
                final Throwable cropError = UCrop.getError(data);
                RxToast.error(cropError.getMessage());
                Log.e("asd", "initMySelfImg: " + cropError.getMessage());
                break;
            default:
                break;
        }
    }

    //从Uri中加载图片 并将其转化成File文件返回
    private File roadImageView(Uri uri, ImageView imageView) {

        Glide.with(this).
                load(uri).
                thumbnail(0.5f).
                into(imageView);


        return (new File(RxPhotoTool.getImageAbsolutePath(this, uri)));
    }

}
